package cn.jbit.smbms.controller;

import java.io.File;
import java.util.*;


import cn.jbit.smbms.Util.AjaxResult;
import cn.jbit.smbms.Util.CommentData;
import cn.jbit.smbms.Util.Pager;
import cn.jbit.smbms.pojo.Role;
import cn.jbit.smbms.pojo.User;
import cn.jbit.smbms.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import cn.jbit.smbms.service.UserService;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;

@RequestMapping("/user")
@Controller
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@RequestMapping("/add")
	public String add(Map<String,Object>map){
		map.put("rolelist",roleService.list());
		return "user/add";
	}
	@RequestMapping("/modify")
	public String modify(Integer id,Map<String,Object>param){
		try {
			User user = userService.queryById(id);
			List<Role> roleList = roleService.list();
			if (user != null && roleList.size()>0) {
				param.put("user",user);
				param.put("roleList",roleList);
			}else{
				throw new RuntimeException("查询用户出错！");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "user/modify";
	}
	@RequestMapping("/domodify")
	public String modify(User user, HttpSession session, @RequestParam("idFile") MultipartFile idFile){

		try {
			User loginUser= (User)session.getAttribute(CommentData.LOGIN_SESSION);
			if (user != null) {
				//根据id查询出user对象，获取以前的图片名称
				User queryById = userService.queryById(user.getId());
				user.setModifyBy(loginUser.getId());
				user.setModifyDate(new Date());
				user.setIdPicPath(queryById.getIdPicPath());
				//文件上传
				//1-上传文件名称
				String originalFilename = idFile.getOriginalFilename();
				//2-获取扩展名
				String ext=originalFilename.substring(originalFilename.lastIndexOf("."));
				//3-设置新的文件名称-防止名称重复
				String newFileName= UUID.randomUUID().toString();
				//4-存放数据库请求路径（真实路径是：file:F://upload/**）

				String separator = File.separator;//获取当前系统的分隔符
				//5-文件存放的真实路径
				String realPath="F:"+separator+"upload"+separator;
				File realfile=new File(realPath);
				if (!realfile.exists()){
					realfile.mkdirs();
				}
				//6-删除这个以前的图片
				File file=new File(realPath+user.getIdPicPath());
				boolean delete = file.delete();
				user.setIdPicPath(newFileName+ext);
				//7-更新数据库表单数据
					int count=userService.update(user);
					if (count==1){
						idFile.transferTo(new File(realPath+newFileName+ext));

					}else{
						throw new RuntimeException("数据库更新用户失败！");
					}


			}else{
				throw new RuntimeException("用户提交的表单为空！");
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

		return "redirect:/user/list";
	}
	@RequestMapping("/view")
	public String view(Integer id,Map<String,Object>param){
		try {
			User user=userService.queryById(id);
			if (user != null) {
				param.put("user",user);
			}else{
				throw new RuntimeException("查询用户出错！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "user/view";
	}
	@RequestMapping("/list")
	public String list(){
		return "user/list";
	}
	@ResponseBody
	@RequestMapping("/delete")
	public Object delete(Integer id){
		AjaxResult result = new AjaxResult();
		try {
			if (id != null) {
				User user = userService.queryById(id);
				String separator = File.separator;//获取当前系统的分隔符
				File file=new File("F:"+separator+"upload"+separator+user.getIdPicPath());//删除对应的文件
				file.delete();
				int count=userService.deleteById(id);
				if (count==1){
					result.setSuccess(true);
				}else{
					throw new RuntimeException("删除出错！");
				}
			}else{
				throw new RuntimeException("用户id为空！");
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMessage(e.getMessage());
		}


		return result;
	}
	@RequestMapping("doadd")
	public String doadd(User user, HttpSession session, @RequestParam("idFile") MultipartFile idFile){

		try {
			User loginUser= (User)session.getAttribute(CommentData.LOGIN_SESSION);
			if (user != null) {
				user.setCreatedBy(loginUser.getId());
				user.setCreationDate(new Date());
				//文件上传
				//1-上传文件名称
				String originalFilename = idFile.getOriginalFilename();
				//2-获取扩展名
				String ext=originalFilename.substring(originalFilename.lastIndexOf("."));
				//3-设置新的文件名称-防止名称重复
				String newFileName= UUID.randomUUID().toString();
				//4-存放数据库请求路径（真实路径是：file:F://upload/**）
				user.setIdPicPath(newFileName+ext);
				String separator=File.separator;
				//5-文件存放的真实路径
				String realPath="F:"+separator+"upload"+separator;
				//6-如果这个路径不存在就创建所需要的文件夹
				File file=new File(realPath);
				if(!file.exists()){
					file.mkdirs();
				}
				//7-插入数据库表单数据
				int count=userService.insert(user);
				if (count==1){
					File saveFile = new File(realPath + newFileName + ext);
					idFile.transferTo(saveFile);
					return "redirect:/user/list";
				}else{
					throw new RuntimeException("数据库新增用户失败！");
				}
			}else{
				throw new RuntimeException("用户提交的表单为空！");
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

		return "user/add";
	}



	@ResponseBody
	@RequestMapping("/dolist")
	public Object dolist(Integer pageSize,Integer pageIndex,String userName,Integer userRole){
		AjaxResult result = new AjaxResult();
		Map<String,Object>param=new HashMap<>();
		try {
			param.put("pageSize",pageSize);
			param.put("pageIndex",pageIndex);
			param.put("start",(pageIndex-1)*pageSize);
			param.put("userName",userName);
			param.put("userRole",userRole);
			param.put("rolelist",roleService.list());
			Pager<User>pager=new Pager<>();
			pager.setPageSize(pageSize);
			pager.setPageIndex(pageIndex);
			int totalCount=userService.queryCountByParam(param);
			pager.setTotalCount(totalCount);
			List<User>userList=userService.queryListByParam(param);
			pager.setList(userList);
			result.setParam(param);
			result.setPage(pager);
			result.setSuccess(true);
		} catch (Exception e) {
			result.setMessage(e.getMessage());
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;
	}
	
}
